package com.es.disped.web.controller.user;

import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.es.disped.api.sms.SmsService;
import com.es.disped.api.user.UserService;
import com.es.disped.common.constant.AliSms;
import com.es.disped.common.constant.RecordStatus;
import com.es.disped.common.model.MsgModel;
import com.es.disped.common.model.PageModel;
import com.es.disped.core.annotation.LogInject;
import com.es.disped.core.controller.BaseController;
import com.es.disped.dao.model.User;
import com.es.disped.dao.model.UserExample;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api("用户信息管理端")
@Controller
@RequestMapping("/manage/user")
public class UserController extends BaseController{
    
	@LogInject
	Logger log;
	@Autowired
	SmsService smsService;
	@Autowired
	UserService userService;
	
	@ApiOperation(value="保存用户对象",httpMethod="POST",response=MsgModel.class,
			notes="教研员保存用户信息（管理端）")
	@RequiresPermissions(value= {"admin:save","sys:save"},logical=Logical.OR)
	@RequestMapping(value="/save",method=RequestMethod.POST)
	public @ResponseBody MsgModel save(@RequestBody @ApiParam(name="user",value="用户对象",required=true) User user)
	{
		int count=0;
		if(Optional.of(user)
				.filter(name->user.getUsername()!=null)
				.filter(psd->user.getPassword()!=null)
				.isPresent())
		{
			user.setUserId(this.getUUID());
			user.setPassword(this.md5(user.getPassword()));
			user.setUserValid(RecordStatus.VERTIFY.getValue());
			count=userService.insertSelective(user);
		}
		this.getSession().setAttribute("registeUser", user);
		return new MsgModel(count==1?HttpStatus.OK.value():HttpStatus.EXPECTATION_FAILED.value(),
				count==1?"保存成功":"保存失败", user);
	}
	
	
	
	@ApiOperation(value="更新用户对象",httpMethod="POST",response=MsgModel.class,
			notes="教研员更新用户信息（管理端）")
	@RequiresPermissions(value= {"admin:update","sys:update"},logical=Logical.OR)
	@RequestMapping(value="/update",method=RequestMethod.POST)
	public @ResponseBody MsgModel update(@RequestBody @ApiParam(name="user",value="用户对象",required=true) User user)
	{
		int count=0;
		if(!this.isNull(user.getPassword()))
		{
			user.setPassword(this.md5(user.getPassword()));
		}
		if(!this.isNull(user.getUserId()))
		{
			count=userService.updateByPrimaryKeySelective(user);
		}
		return new MsgModel(count==1?HttpStatus.OK.value():HttpStatus.EXPECTATION_FAILED.value(),
				count==1?"更新成功":"更新失败", user);
	}
	
	
	@ApiOperation(value="检索用户对象",httpMethod="POST",response=MsgModel.class,
			notes="教研员检索用户信息（管理端）")
	@RequiresPermissions(value= {"admin:select","sys:select"},logical=Logical.OR)
	@RequestMapping(value="/list",method=RequestMethod.POST)
	public @ResponseBody MsgModel list(@RequestBody @ApiParam(name="user",value="用户对象",required=false) User user)
	{
		UserExample listExample=new UserExample();
		UserExample.Criteria criteria=listExample.createCriteria();
		criteria.andUserValidNotEqualTo(RecordStatus.VERTIFY.getValue());
		if(!this.isNull(user.getUsername()))
		{
			criteria.andUsernameLike("%"+user.getUsername()+"%");
		}
		if(!this.isNull(user.getUserId()))
		{
			criteria.andUserIdEqualTo(user.getUserId());
		}
		if(!this.isNull(user.getPhone()))
		{
			criteria.andPhoneLike("%"+user.getPhone()+"%");
		}
		if(!this.isNull(user.getUserType()))
		{
			criteria.andUserTypeEqualTo(user.getUserType());
		}
		List<User> users=userService.selectByExample(listExample);
		return new MsgModel(users.size()>0?HttpStatus.OK.value():HttpStatus.EXPECTATION_FAILED.value(),
				users.size()>0?"列表加载成功":"列表加载失败", users);
	}
	
	
	@ApiOperation(value="分页获取用户列表",httpMethod="POST",response=MsgModel.class,notes="管理员获取用户信息（管理端），分页加载")
	@RequiresPermissions(value= {"admin:select","sys:select"},logical=Logical.OR)
	@RequestMapping(value="/pages",method=RequestMethod.POST)
	public @ResponseBody MsgModel pages(@RequestBody @ApiParam(name="paramMap",value="分页参数[offset,limit]",required=true) Map<String, Object> paramMap)
	{
		UserExample userExample=new UserExample();
		userExample.createCriteria().andUserValidNotEqualTo(RecordStatus.VERTIFY.getValue());
		userExample.setOrderByClause("join_date desc");
		PageModel<User> pageModel=null;
		if(Optional.of(paramMap)
		.filter(offset->paramMap.containsKey("offset")!=false)
		.filter(limit->paramMap.containsKey("limit")!=false)
		.isPresent())
		{
			pageModel=userService.selectByExampleForOffsetPage(userExample,
					Integer.valueOf(paramMap.get("offset").toString()), Integer.valueOf(paramMap.get("limit").toString()));
		}
		return new MsgModel(pageModel!=null?HttpStatus.OK.value():HttpStatus.EXPECTATION_FAILED.value(),
		pageModel!=null?"":"用户列表为空", pageModel!=null?pageModel:"");
	}
	
	
	@ApiOperation(value="获取待审核新用户列表",httpMethod="POST",response=MsgModel.class,	notes="管理员获取待审核新用户信息（管理端），分页加载")
	@RequiresPermissions(value= {"admin:select","sys:select"},logical=Logical.OR)
	@RequestMapping(value="/vertifyUserList",method=RequestMethod.POST)
	public @ResponseBody MsgModel vertifyUserList(@RequestBody @ApiParam(name="paramMap",value="分页参数[offset,limit]",required=true) Map<String, Object> paramMap)
	{
		UserExample userExample=new UserExample();
		int offset=(int) paramMap.get("offset");
		int limit=(int) paramMap.get("limit");
		userExample.createCriteria().andUserValidEqualTo(RecordStatus.VERTIFY.getValue());
		PageModel<User> users=userService.selectByExampleForOffsetPage(userExample, offset, limit);
		return new MsgModel(this.isNull(users)?HttpStatus.NOT_FOUND.value():HttpStatus.OK.value(),
				this.isNull(users)?"没有待审核用户":"",this.isNull(users)?null:users);
	}
	
	
	
	@ApiOperation(value="审核新用户",httpMethod="POST",response=MsgModel.class,
			notes="教研员审核新用户信息，需用户提交ID及手机号、状态更新值（管理端）")
	@RequiresPermissions(value= {"admin:update","sys:update"},logical=Logical.OR)
	@RequestMapping(value="/vertify",method=RequestMethod.POST)
	public @ResponseBody MsgModel vertify(@RequestBody @ApiParam(name="user",value="用户对象",required=true) User user)
	{
		int count=0;
		 if(Optional.of(user)
				 .filter(userId->user.getUserId()!=null)
				 .isPresent())
		 {
			 user.setUserValid(RecordStatus.USEAGE.getValue());
			 count=userService.updateByPrimaryKeySelective(user);
		 }
		 //审核通过，短信通知
		 if(count==1)
		 {
			 smsService.sendMessage(AliSms.ALI_MESSAGE_SIGN_NAME.ES_TECH.getValue(), user.getPhone(),
					 AliSms.ALI_MESSAGE_TEMPLATE_CODE.PASSWORD_RESET.getValue(), null);
		 }
		 return new MsgModel(count==1?HttpStatus.OK.value():HttpStatus.EXPECTATION_FAILED.value(),
				 count==1?"":"审核不通过");
	}
}